package com.ajouroid.smartcoworker;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class InitialActivity extends Activity {
	
	String team_id = null;
	List<String> slides = null;
	boolean mode = true;
	Bitmap[] slide_img = null;
	
	int cur_page = 0;
	
	
	ImageButton imgbtn_presentation_mode;
	ImageButton imgbtn_meeting_mode;
	ImageView iv_myprofile;
	ProgressBar pb_imgloading;
	TextView tv_myid;
	
	
	ArrayList<User> mem_list;
	ArrayList<User> tmp_list;
	String myId = null;
	String imgName = null;
	
	//뒤로 두번눌러 종료 구현
	private boolean m_bFlag = false;
	private Handler mBackClickHandler;

	final String TAG = "InitialActivity";

	final int EXPLORER_ACTIVITY = 101;
	final int ADDFRIENDS_ACTIVITY = 102;
	
	BroadcastReceiver mReceiver = new BroadcastReceiver()
	{
		@Override
		public void onReceive(Context arg0, Intent arg1) {
			String type = arg1.getStringExtra("type");
			String msg = arg1.getStringExtra("content");
						
			try {
				//JSONObject obj = new JSONObject(msg);
				
				if (type.equals("team_info"))
				{
					Team t = Team.parseFromString(msg);
					
					if (owner)
					{
						if (uploadDialog.isShowing())
							uploadDialog.dismiss();
						
						if(mode)
						{
							Intent i = new Intent(InitialActivity.this, MainActivity.class);
							i.putExtra("id", myId);
							i.putExtra("image", imgName);
							i.putExtra("team_info", msg);
							startActivity(i);
							finish();
						}
						else
						{
							Intent i = new Intent(InitialActivity.this, MeetingActivity.class);
							i.putExtra("id", myId);
							i.putExtra("image", imgName);
							i.putExtra("team_info", msg);
							i.putExtra("role", "sender");
							startActivity(i);
							finish();
							
						}
					}
					else
					{
						new AlertDialog.Builder(InitialActivity.this)
						.setTitle("Invite Message Arrived")
						.setMessage("Team Leader: " + t.leader + "\n")
						.setPositiveButton("Ok", new AcceptTeamListener(msg))
						.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
							
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						})
						.show();
					}
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		
	};
	
	private class AcceptTeamListener implements DialogInterface.OnClickListener
	{
		String msg;
		
		public AcceptTeamListener(String _msg)
		{
			msg = _msg;
		}

		public void onClick(DialogInterface dialog, int which) {
			Team t = Team.parseFromString(msg);
			if (t.type.equalsIgnoreCase("presentation"))
			{
				Intent i = new Intent(InitialActivity.this, MainActivity.class);
				i.putExtra("id", myId);
				i.putExtra("image", imgName);
				i.putExtra("team_info", msg);
				startActivity(i);
				finish();
			}
			else
			{
				Intent i = new Intent(InitialActivity.this, MeetingActivity.class);
				i.putExtra("id", myId);
				i.putExtra("image", imgName);
				i.putExtra("team_info", msg);
				i.putExtra("role", "receiver");
				startActivity(i);
				finish();
			}
		}
		
	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_initial);
        
        Toast.makeText(InitialActivity.this, R.string.initial_notice, Toast.LENGTH_SHORT).show();
        
        mBackClickHandler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				if(msg.what == 0) {
					m_bFlag = false;
				}
			}
		};
        
        imgbtn_presentation_mode = (ImageButton) findViewById(R.id.initial_btn_pm);
        imgbtn_meeting_mode = (ImageButton) findViewById(R.id.initial_btn_mm);
        iv_myprofile = (ImageView)findViewById(R.id.initial_myprofile);
        tv_myid = (TextView)findViewById(R.id.initial_myid);
        pb_imgloading = (ProgressBar)findViewById(R.id.initial_prog_bar);
        
        Intent i = getIntent();
        
        if (i.hasExtra("id"))
        {
        	myId = i.getStringExtra("id");
        	tv_myid.setText(myId);
        	
        	// set profile image
        	imgName = i.getStringExtra("image");
        	if (imgName != null && !imgName.equals("null"))
        	{
        		iv_myprofile.setVisibility(View.GONE);
        		pb_imgloading.setVisibility(View.VISIBLE);
	        	GetImageTask imgTask = new GetImageTask(iv_myprofile,pb_imgloading);
	        	imgTask.execute(myId);
        	}
        	else{
        		pb_imgloading.setVisibility(View.GONE);
        	}
        }

        else
        {
        	Log.d(TAG, "no id");
        	finish();
        }
        mem_list = new ArrayList<User>();
    }
    
    public boolean onKeyDown(int KeyCode, KeyEvent event){
		super.onKeyDown(KeyCode, event);

		if(event.getAction() == KeyEvent.ACTION_DOWN) {
			switch(KeyCode) {
			case KeyEvent.KEYCODE_BACK:	// `뒤로` 키와 같은 기능을 한다.
				if(!m_bFlag) {
					Toast.makeText(getApplicationContext(), "'뒤로'버튼을 한번 더 누르시면 종료됩니다",     Toast.LENGTH_SHORT).show();
					m_bFlag = true;
					mBackClickHandler.sendEmptyMessageDelayed(0, 2000);

					return false;
				}
				else {
					DeleteCache del = new DeleteCache();
					del.clearCache(this);
					finish();
				}
				return true;
			}
		}

		return false;
	}
    
    

    
    @Override
    public void onResume()
    {
    	super.onResume();
    	
    	this.registerReceiver(mReceiver, new IntentFilter("edu.ajou.smartcoworker.PUSHMSG"));
    	
    	//팀원정보 가져와서 mem_list 에 넣어둬야 함.
    	
    	imgbtn_presentation_mode.setOnClickListener(new OnClickListener () {

			public void onClick(View v) {
				mode = true;
				Intent i = new Intent(InitialActivity.this, AddFriendsActivity.class);
				i.putExtra("myId", myId);
				i.putExtra("exist_list", mem_list);
				startActivityForResult(i, ADDFRIENDS_ACTIVITY);
			}
    	});
    	imgbtn_meeting_mode.setOnClickListener(new OnClickListener () {

			public void onClick(View v) {
				mode = false;
				Intent i = new Intent(InitialActivity.this, AddFriendsActivity.class);
				i.putExtra("myId", myId);
				i.putExtra("exist_list", mem_list);
				startActivityForResult(i, ADDFRIENDS_ACTIVITY);
			}
    	});
    	
    }
    
    @Override
    public void onStop() {
    	
    	super.onStop();
    }
    
    
    
    @Override
    public void onDestroy() {
    	this.unregisterReceiver(mReceiver);
    	super.onDestroy();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }


	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode)
		{
		case ADDFRIENDS_ACTIVITY:
			if(resultCode == RESULT_OK){
				tmp_list = (ArrayList<User>) data.getExtras().getSerializable("add_list");
				for(int i=0;  i<tmp_list.size(); i++){
					mem_list.add(tmp_list.get(i));
				}
				
				Intent intent = new Intent(InitialActivity.this, ExplorerActivity.class);
				startActivityForResult(intent, EXPLORER_ACTIVITY);
			}
		case EXPLORER_ACTIVITY:
			if(resultCode == RESULT_OK){
				if (data != null && data.hasExtra("path"))
				{
					String filePath = data.getStringExtra("path");
					Toast.makeText(this, filePath, Toast.LENGTH_SHORT).show();

					UploadFileTask task = new UploadFileTask(this);
					task.execute(filePath,mem_list); //여기에 팀원리스트
				}
			}
			else{
				mem_list.clear();
			}
		}
		
		super.onActivityResult(requestCode, resultCode, data);
	}
	
	public boolean owner = false;
	
	ProgressDialog uploadDialog;
	
	class UploadFileTask extends AsyncTask<Object, Integer, String>
	{
		HttpConnector conn;
		Context mCtx;
		
		
		public UploadFileTask(Context context)
		{
			mCtx = context;
		}
		@Override
		protected void onPreExecute() {
			conn = new HttpConnector();
			
			uploadDialog = new ProgressDialog(mCtx);
			uploadDialog.setTitle("Wait please...");
			uploadDialog.setMessage("Uploading the file...");
			uploadDialog.setCancelable(false);
			uploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			
			uploadDialog.show();
			
			owner=true;
			
			super.onPreExecute();
		}

		@Override
		protected String doInBackground(Object... arg0) {
			ArrayList<String> members = new ArrayList<String>();
			@SuppressWarnings("unchecked")
			ArrayList<User> arr = (ArrayList<User>)arg0[1];
			// TODO 멤버 추가
			members.add(myId);
			
			for(int i=0; i<arr.size(); i++){
				members.add(arr.get(i).getId());
			}
			
			String type = mode?"presentation":"meeting";
			String resp = conn.createTeam(myId, type, members, (String)arg0[0]);
			return resp;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Log.d(TAG, "Team created.");
			if (uploadDialog.isShowing())
			{
				uploadDialog.setMessage("Processing the file...");
				//uploadDialog.dismiss();
			}
			/*
			Intent i = new Intent(mCtx, MainActivity.class);
			i.putExtra("id", myId);
			i.putExtra("team_info", result);
			dialog.dismiss();
			mCtx.startActivity(i);
			finish();
			*/
		}
	}
	
	
}
